package com.swfee.qinben;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import android.app.LocalActivityManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.RelativeLayout;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TextView;

import com.swfee.qinben.PopMenu.OnItemClickListener;
import com.swfee.qinben.base.AppBaseActivity;
import com.swfee.qinben.base.BackKeyExitService;

public class QinBenActivity extends AppBaseActivity implements OnClickListener,
		OnItemClickListener,BackKeyExitService{

	private PopMenu popMenu;

	public final List<View> listViews = new ArrayList<View>();

	public Context context = null;

	public LocalActivityManager manager = null;

	public TabHost tabHost = null;

	public ViewPager pager = null;

	public final String titles[] = new String[]{"","","",""};
	public int initPage[][];

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		findViewById(R.id.btn_title_popmenu).setOnClickListener(this);

		// 初始化弹出菜单
		popMenu = new PopMenu(this);
		List<Map> menuMaps = new ArrayList<Map>();
		String[] txts = new String[] { "信息", "日程事项", "联系人", "预约管理", "监控管理",
				"设置", "关于亲本", "更换账号", "退出程序" };
		Integer[] imgIds = new Integer[] { 
				R.drawable.ico_msg,
				R.drawable.ico_schedue, R.drawable.ico_set,
				R.drawable.ico_arrange, R.drawable.ico_monitor, R.drawable.ico_set,
				R.drawable.ico_aboutme, R.drawable.ico_logout, R.drawable.ico_exit };

		for (int i = 0; i < txts.length; i++) {
			Map map1 = new HashMap();
			map1.put("textView", txts[i]);
			map1.put("imgTitle", imgIds[i]);
			menuMaps.add(map1);
		}

		popMenu.addItems(menuMaps);

		// 加载viewPager
		context = this;
		pager = (ViewPager) findViewById(R.id.viewpager);

		// 定放一个放view的list，用于存放viewPager用到的view
		// listViews = new LinkedList<View>();

		manager = new LocalActivityManager(this, true);
		manager.dispatchCreate(savedInstanceState);

		tabHost = (TabHost) findViewById(R.id.tabhost);
		tabHost.setup();
		tabHost.setup(manager);

		// 这儿主要是自定义一下tabhost中的tab的样式
		RelativeLayout tabIndicator[] = new RelativeLayout[4];
		for (int i = 0; i < 4; i++) {
			tabIndicator[i] = (RelativeLayout) LayoutInflater.from(this)
					.inflate(R.layout.tabwidget, null);
		}

		// {0,0}//表示index和是否初始化， {i,1}表示 第i个已初始化
		initPage = new int[][] { { 0, 0 }, { 1, 0 }, { 2, 0 }, { 3, 0 } };

		int[] backDrawables = { R.drawable.bg_tabwidget_msg,
				R.drawable.bg_tabwidget_contact,
				R.drawable.bg_tabwidget_calendar, R.drawable.bg_tabwidget_set };
		String[] msgTypes = "信息,联系人,日程 ,设置".split(",");
		for (int i = 0; i < tabIndicator.length; i++) {
			TextView tvTab = (TextView) tabIndicator[i]
					.findViewById(R.id.tv_title);
			View iv_mark = (View) tabIndicator[i].findViewById(R.id.iv_mark);
			iv_mark.setBackgroundDrawable(getResources().getDrawable(
					backDrawables[i]));
			tvTab.setText(msgTypes[i]);
		}

		Intent intent = new Intent(context, EmptyActivity.class);
		// 注意这儿Intent中的activity不能是自身
		// 比如“A”对应的是T1Activity，后面intent就new的T3Activity的。
		for (int index = 0; index < 4; index++) {
			tabHost.addTab(tabHost.newTabSpec("T" + (index))
					.setIndicator(tabIndicator[index]).setContent(intent));

		}

		// 初始化为显示 第一个
		Intent i1 = new Intent(context, T1Activity.class);
		listViews.add(getView("T" + 0, i1));
		Intent i2 = new Intent(context, EmptyActivity.class);
		listViews.add(getView("T1", i2));
		Intent i3 = new Intent(context, EmptyActivity.class);
		listViews.add(getView("T2", i3));
		Intent i4 = new Intent(context, EmptyActivity.class);
		listViews.add(getView("T3", i4));

		pager.setCurrentItem(0);
		initPage[0][1] = 1;

		pager.setAdapter(new MyPageAdapter(listViews));
		pager.setOnPageChangeListener(new OnPageChangeListener() {
			@Override
			public void onPageSelected(int position) {
				// 当viewPager发生改变时，同时改变tabhost上面的currentTab
				tabHost.setCurrentTab(position);
				
			}

			@Override
			public void onPageScrolled(int arg0, float arg1, int arg2) {
			}

			@Override
			public void onPageScrollStateChanged(int arg0) {
			}
		});

		// 点击tabhost中的tab时，要切换下面的viewPager
		tabHost.setOnTabChangedListener(new OnTabChangeListener() {
			@Override
			public void onTabChanged(String tabId) {

				int index = Integer.parseInt(tabId.charAt(1) + "");
				if (initPage[index][1] == 0) {
					String className = "com.swfee.qinben." + "T" + (index + 1)
							+ "Activity";
					Class c = null;
					try {
						c = Class.forName(className);
					} catch (ClassNotFoundException e) {
						e.printStackTrace();
					}
					Intent i1 = new Intent(context, c);
					initPage[index][1] = 1;
					reLoadViews(index, c, null);
				}
				pager.setCurrentItem(index);
				setHeaderTitleCur();
			}

		});

	}

	@Override
	public void onClick(View v) {
		if (v.getId() == R.id.btn_title_popmenu) {
			popMenu.showAsDropDown(v);
		}
	}

	@Override
	public void onItemClick(int index) {
		// Toast.makeText(this, "item clicked " + index + "!",
		// Toast.LENGTH_SHORT)
		// .show();
	}

	public View getView(String id, Intent intent) {
		return manager.startActivity(id, intent).getDecorView();
	}

	public class MyPageAdapter extends PagerAdapter {

		private List<View> list;

		public MyPageAdapter(List<View> list) {
			this.list = list;
		}

		@Override
		public void destroyItem(View view, int position, Object arg2) {
			ViewPager pViewPager = ((ViewPager) view);
			pViewPager.removeView(list.get(position));
		}

		@Override
		public void finishUpdate(View arg0) {
		}

		@Override
		public int getCount() {
			return list.size();
		}

		@Override
		public Object instantiateItem(View view, int position) {
			ViewPager pViewPager = ((ViewPager) view);
			pViewPager.addView(list.get(position));
			return list.get(position);
		}

		@Override
		public boolean isViewFromObject(View arg0, Object arg1) {
			return arg0 == arg1;
		}

		@Override
		public void restoreState(Parcelable arg0, ClassLoader arg1) {
		}

		@Override
		public Parcelable saveState() {
			return null;
		}

		@Override
		public void startUpdate(View arg0) {
		}

	}

	public void reLoadViews(int index, Class class1, Bundle bundle) {

		String className = class1.getName();
		Class c = null;
		try {
			c = Class.forName(className);
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		Intent i1 = new Intent(this, c);
		listViews.remove(index);
		listViews.add(index, getView("T" + index, i1));

		pager.removeAllViews();
		pager.setAdapter(new MyPageAdapter(listViews));
		pager.setCurrentItem(index);
	}
	
	public void setHeaderTitle(String str,int index){
		TextView header = (TextView) findViewById(R.id.tv_headerTitle);
		header.setText(str);
		titles[index] = str;
	}
	
	public void setHeaderTitleCur(){
		TextView header = (TextView) findViewById(R.id.tv_headerTitle);
		int i = pager.getCurrentItem();
		header.setText(titles[i]);
	}
	
	
	
}